package com.wiloon.java8x.io.file;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA. User: wiloon Date: 9/2/12 Time: 12:20 PM
 */
public class FileHelper {

	public String read(String path) {
		StringBuffer sb = new StringBuffer();
		FileReader reader = null;
		try {
			reader = new FileReader(path);
			BufferedReader br = new BufferedReader(reader);
			String s1 = null;
			while ((s1 = br.readLine()) != null) {
				sb.append(s1);
			}
			br.close();
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		} catch (IOException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		}

		return sb.toString();
	}

	public String read(InputStream stream) {
		StringBuffer sb = new StringBuffer();
		// FileReader reader = null;
		// try {
		// reader = new FileReader(path);
		// BufferedReader br = new BufferedReader(reader);
		// String s1 = null;
		// while ((s1 = br.readLine()) != null) {
		// sb.append(s1);
		// }
		// br.close();
		// reader.close();
		// } catch (FileNotFoundException e) {
		// e.printStackTrace(); //To change body of catch statement use File |
		// Settings | File Templates.
		// } catch (IOException e) {
		// e.printStackTrace(); //To change body of catch statement use File |
		// Settings | File Templates.
		// }

		return sb.toString();
	}

	// find out all files under one specified folder
	public List<File> getFilesUnderFolder(String folderPath) {
		List<File> rtnList = new ArrayList<File>();
		// get file and folders under folder
		File folder = new File(folderPath);
		File[] files = folder.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				rtnList.addAll(getFilesUnderFolder(file.getAbsolutePath()));
			} else {
				rtnList.add(file);
			}
		}
		return rtnList;
	}

	public void copyFile(String sourceFile, String targetFile)
			throws IOException {
		FileChannel in = null;
		FileChannel out = null;
		FileInputStream inStream = null;
		FileOutputStream outStream = null;
		try {
			inStream = new FileInputStream(sourceFile);
			outStream = new FileOutputStream(targetFile);
			in = inStream.getChannel();
			out = outStream.getChannel();
			in.transferTo(0, in.size(), out);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			inStream.close();
			in.close();
			outStream.close();
			out.close();

		}
	}

	public ImgFile readImg(String path) {
		File picFile = new File(path);
		BufferedImage image = null;
		try {
			image = ImageIO.read(picFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ImgFile img = new ImgFile();
		img.setWidth(image.getWidth());
		img.setHeight(image.getHeight());
		img.setFilePath(path);
		return img;
	}
}
